package com.example.demo.service.impl;

import com.example.demo.entity.Article;
import com.example.demo.entity.Tag;
import com.example.demo.exception.BusinessException;
import com.example.demo.mapper.ArticleMapper;
import com.example.demo.service.ArticleService;
import com.example.demo.service.CategoryService;
import com.example.demo.service.TagService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 文章服务实现类
 * 实现文章相关的业务逻辑
 */
@Service
public class ArticleServiceImpl implements ArticleService {
    
    private static final Logger log = LoggerFactory.getLogger(ArticleServiceImpl.class);
    
    private final ArticleMapper articleMapper;
    private final TagService tagService;
    private final CategoryService categoryService;
    
    /**
     * 构造器注入
     */
    public ArticleServiceImpl(ArticleMapper articleMapper, TagService tagService, CategoryService categoryService) {
        this.articleMapper = articleMapper;
        this.tagService = tagService;
        this.categoryService = categoryService;
    }
    
    @Override
    public Article getArticleById(Long id, boolean incrementView) {
        log.info("获取文章详情，ID：{}，是否增加阅读量：{}", id, incrementView);
        
        Article article = articleMapper.selectById(id);
        if (article == null) {
            throw new BusinessException("文章不存在");
        }
        
        // 获取文章标签
        List<Tag> tags = articleMapper.selectTagsByArticleId(id);
        article.setTags(tags);
        
        // 如果需要增加阅读量
        if (incrementView && article.getStatus() == Article.Status.PUBLISHED) {
            articleMapper.incrementViewCount(id, 1);
            article.setViewCount(article.getViewCount() + 1);
        }
        
        return article;
    }
    
    @Override
    public PageResult<Article> getArticleList(int page, int size, Long categoryId, Integer status, String keyword) {
        log.info("分页查询文章列表，页码：{}，大小：{}，分类：{}，状态：{}，关键词：{}", page, size, categoryId, status, keyword);
        
        // 参数验证
        if (page < 1) page = 1;
        if (size < 1) size = 10;
        
        int offset = (page - 1) * size;
        
        // 查询文章列表
        List<Article> articles = articleMapper.selectArticleList(offset, size, categoryId, status, keyword);
        
        // 为每篇文章获取标签
        for (Article article : articles) {
            List<Tag> tags = articleMapper.selectTagsByArticleId(article.getId());
            article.setTags(tags);
        }
        
        // 查询总数
        int total = articleMapper.countArticles(categoryId, status, keyword);
        
        return new PageResult<>(articles, total, page, size);
    }
    
    @Override
    public List<Article> getTopArticles(int limit) {
        List<Article> articles = articleMapper.selectTopArticles(limit);
        
        // 为每篇文章获取标签
        for (Article article : articles) {
            List<Tag> tags = articleMapper.selectTagsByArticleId(article.getId());
            article.setTags(tags);
        }
        
        return articles;
    }
    
    @Override
    public List<Article> getRecentArticles(int limit) {
        List<Article> articles = articleMapper.selectRecentArticles(limit);
        
        // 为每篇文章获取标签
        for (Article article : articles) {
            List<Tag> tags = articleMapper.selectTagsByArticleId(article.getId());
            article.setTags(tags);
        }
        
        return articles;
    }
    
    @Override
    public List<Article> getPopularArticles(int limit) {
        List<Article> articles = articleMapper.selectPopularArticles(limit);
        
        // 为每篇文章获取标签
        for (Article article : articles) {
            List<Tag> tags = articleMapper.selectTagsByArticleId(article.getId());
            article.setTags(tags);
        }
        
        return articles;
    }
    
    @Override
    public PageResult<Article> getArticlesByTag(Long tagId, int page, int size) {
        if (page < 1) page = 1;
        if (size < 1) size = 10;
        
        int offset = (page - 1) * size;
        List<Article> articles = articleMapper.selectArticlesByTag(tagId, offset, size);
        
        // 为每篇文章获取标签
        for (Article article : articles) {
            List<Tag> tags = articleMapper.selectTagsByArticleId(article.getId());
            article.setTags(tags);
        }
        
        // 暂时使用简单的总数计算，实际应该有专门的count方法
        long total = articles.size();
        
        return new PageResult<>(articles, total, page, size);
    }
    
    @Override
    public PageResult<Article> getArticlesByAuthor(Long authorId, int page, int size) {
        if (page < 1) page = 1;
        if (size < 1) size = 10;
        
        int offset = (page - 1) * size;
        List<Article> articles = articleMapper.selectArticlesByAuthor(authorId, offset, size);
        
        // 为每篇文章获取标签
        for (Article article : articles) {
            List<Tag> tags = articleMapper.selectTagsByArticleId(article.getId());
            article.setTags(tags);
        }
        
        long total = articles.size();
        
        return new PageResult<>(articles, total, page, size);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Article createArticle(Article article, List<String> tagNames) {
        log.info("创建文章，标题：{}", article.getTitle());
        
        // 参数验证
        if (!StringUtils.hasText(article.getTitle())) {
            throw new BusinessException("文章标题不能为空");
        }
        if (!StringUtils.hasText(article.getContent())) {
            throw new BusinessException("文章内容不能为空");
        }
        if (article.getAuthorId() == null) {
            throw new BusinessException("作者不能为空");
        }
        
        // 设置默认值
        LocalDateTime now = LocalDateTime.now();
        article.setCreateTime(now);
        article.setUpdateTime(now);
        article.setViewCount(0L);
        article.setLikeCount(0L);
        article.setCommentCount(0L);
        
        if (article.getStatus() == null) {
            article.setStatus(Article.Status.DRAFT);
        }
        if (article.getIsTop() == null) {
            article.setIsTop(0);
        }
        
        // 如果状态是发布，设置发布时间
        if (article.getStatus() == Article.Status.PUBLISHED) {
            article.setPublishTime(now);
        }
        
        // 插入文章
        int rows = articleMapper.insert(article);
        if (rows != 1) {
            throw new BusinessException("创建文章失败");
        }
        
        // 处理标签
        if (tagNames != null && !tagNames.isEmpty()) {
            List<Tag> tags = tagService.getOrCreateTags(tagNames);
            for (Tag tag : tags) {
                articleMapper.insertArticleTag(article.getId(), tag.getId());
                tagService.incrementArticleCount(tag.getId(), 1);
            }
        }
        
        // 更新分类文章数量
        if (article.getCategoryId() != null) {
            categoryService.updateArticleCount(article.getCategoryId());
        }
        
        log.info("文章创建成功，ID：{}", article.getId());
        return article;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Article updateArticle(Article article, List<String> tagNames) {
        log.info("更新文章，ID：{}", article.getId());
        
        Article existingArticle = articleMapper.selectSimpleById(article.getId());
        if (existingArticle == null) {
            throw new BusinessException("文章不存在");
        }
        
        // 保存旧的分类ID
        Long oldCategoryId = existingArticle.getCategoryId();
        
        // 更新文章
        article.setUpdateTime(LocalDateTime.now());
        
        // 如果状态改为发布且之前没有发布时间，设置发布时间
        if (article.getStatus() == Article.Status.PUBLISHED && existingArticle.getPublishTime() == null) {
            article.setPublishTime(LocalDateTime.now());
        }
        
        int rows = articleMapper.update(article);
        if (rows != 1) {
            throw new BusinessException("更新文章失败");
        }
        
        // 处理标签更新
        if (tagNames != null) {
            // 获取旧标签
            List<Tag> oldTags = articleMapper.selectTagsByArticleId(article.getId());
            
            // 删除所有旧的标签关联
            articleMapper.deleteArticleTags(article.getId());
            
            // 减少旧标签的使用次数
            for (Tag oldTag : oldTags) {
                tagService.incrementArticleCount(oldTag.getId(), -1);
            }
            
            // 添加新标签
            if (!tagNames.isEmpty()) {
                List<Tag> newTags = tagService.getOrCreateTags(tagNames);
                for (Tag tag : newTags) {
                    articleMapper.insertArticleTag(article.getId(), tag.getId());
                    tagService.incrementArticleCount(tag.getId(), 1);
                }
            }
        }
        
        // 更新分类文章数量
        if (oldCategoryId != null && !oldCategoryId.equals(article.getCategoryId())) {
            categoryService.updateArticleCount(oldCategoryId);
        }
        if (article.getCategoryId() != null) {
            categoryService.updateArticleCount(article.getCategoryId());
        }
        
        return articleMapper.selectById(article.getId());
    }
    
    @Override
    public boolean publishArticle(Long id) {
        Article article = articleMapper.selectSimpleById(id);
        if (article == null) {
            throw new BusinessException("文章不存在");
        }
        
        article.setStatus(Article.Status.PUBLISHED);
        if (article.getPublishTime() == null) {
            article.setPublishTime(LocalDateTime.now());
        }
        
        return articleMapper.updateStatus(id, Article.Status.PUBLISHED) == 1;
    }
    
    @Override
    public boolean hideArticle(Long id) {
        return articleMapper.updateStatus(id, Article.Status.HIDDEN) == 1;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteArticle(Long id) {
        log.info("删除文章，ID：{}", id);
        
        Article article = articleMapper.selectSimpleById(id);
        if (article == null) {
            return false;
        }
        
        // 获取文章标签并减少使用次数
        List<Tag> tags = articleMapper.selectTagsByArticleId(id);
        for (Tag tag : tags) {
            tagService.incrementArticleCount(tag.getId(), -1);
        }
        
        // 删除文章（会自动删除标签关联）
        int rows = articleMapper.deleteById(id);
        
        // 更新分类文章数量
        if (article.getCategoryId() != null) {
            categoryService.updateArticleCount(article.getCategoryId());
        }
        
        return rows == 1;
    }
    
    @Override
    public boolean likeArticle(Long id) {
        return articleMapper.incrementLikeCount(id, 1) == 1;
    }
    
    @Override
    public List<Tag> getArticleTags(Long articleId) {
        return articleMapper.selectTagsByArticleId(articleId);
    }
    
    @Override
    public long getTotalArticleCount() {
        return articleMapper.selectTotalCount();
    }
    
    @Override
    public long getTotalViewCount() {
        return articleMapper.selectTotalViewCount();
    }
}
